﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace ClientLibrary
{
    public class PDFtoImage
    {
        private string ghostScriptPath = "";
        private string output = "";
        
        public PDFtoImage(string filename, string ghostscriptpath)
        {
            this.ghostScriptPath = ghostscriptpath + "\\gswin32.exe";
            string currentdirectory = Directory.GetCurrentDirectory();
            this.output = @"TEMP_IMAGES\"+filename+"_"+DateTime.Now.Year.ToString()+"_"+DateTime.Now.Month.ToString()+"_"+DateTime.Now.Day.ToString()+"_"+DateTime.Now.Hour.ToString()+DateTime.Now.Minute.ToString()+DateTime.Now.Second.ToString();            
        }

        public string CopyFilePDF(string path, string filename)
        {
            File.Copy(path+@"\"+filename, @"EXPORT\PDF\"+this.ReplaceWhiteSpaces(filename), true);
            return @"EXPORT\PDF\" + this.ReplaceWhiteSpaces(filename);
        }

        private string ReplaceWhiteSpaces(string str)
        {
            return System.Text.RegularExpressions.Regex.Replace(str, @"\s+", "-");
        }

        public string PdfToJpg(string input, int batchid)
        {
            string outfilename = this.output + "_batchid_" + batchid.ToString();            
            outfilename = this.ReplaceWhiteSpaces(outfilename);
            Console.WriteLine("outfilename: "+outfilename);
            String ars = @"-dNOPAUSE -sDEVICE=jpeg -r300 -o" + outfilename + "-%d.jpg " + input;
            //Console.WriteLine("output: "+this.output+" input: "+input);
            Process proc = new Process();
            proc.StartInfo.FileName = this.ghostScriptPath;
            proc.StartInfo.Arguments = ars;
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.Start();
            proc.WaitForExit();
            return outfilename;
        }
    }
}
